package top.txl.exception;

import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.ReflectionException;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.dao.DuplicateKeyException;
import top.txl.entity.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


import java.sql.SQLIntegrityConstraintViolationException;

// 全局异常处理器
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(DuplicateKeyException.class)
    public R<String> ex(SQLIntegrityConstraintViolationException e){
        log.info("异常捕获");
        Boolean isTrue = e.getMessage().contains("Duplicate entry");
        log.info("值,{}",isTrue);
        if(isTrue){
            return R.error("名字已经存在");
        }
        e.printStackTrace();
        return R.error("未知异常");
    }

    @ExceptionHandler(MyBatisSystemException.class)
    public R<String> ex(ReflectionException r){
        log.info("异常捕获{}",r.getMessage());
        Boolean other = r.getMessage().contains("There is no getter");
        if(other){
            return R.error("服务端参数错误");
        }
        r.printStackTrace();
        return R.error("未知异常 named");
    }

    /***
     * 自定义异常
     * @param r
     * @return R
     */
    @ExceptionHandler(CustomerException.class)
    public R<String> ex(CustomerException r){
        log.info("异常捕获{}",r.getMessage());
        String msg = r.getMessage();
        return R.error(msg);
    }

    @ExceptionHandler(ExpiredJwtException.class)
    public R<String> ex(ExpiredJwtException r){
        log.info("token过期异常，{}",r.getMessage());
        boolean isTrue = r.getMessage().contains("JWT expired at");
        if(isTrue){
            return R.error("token已失效");
        }
        return R.error("未知异常 token");
    }

    @ExceptionHandler(Exception.class)
    public R<String> ex(Exception e){
        e.printStackTrace();
        return R.error("未知异常 exception");
    }
}
